package com.xingfly.util;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import com.xingfly.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by SuperS on 2016/12/16.
 */
@Service
public class CaptchaUtil {
    @Autowired
    private CaptchaService captchaService;
    private Properties props = new Properties();
    private Producer kaptchaProducer = null;
    private String sessionKeyValue = null;
    private String sessionKeyDateValue = null;

    /**
     * 配置验证码生成类的基本信息
     */
    public CaptchaUtil() {
        ImageIO.setUseCache(false);
        this.props.put("kaptcha.border", "yes");
        this.props.put("kaptcha.border.color", "105,179,90");
        this.props.put("kaptcha.textproducer.font.color", "black");
        this.props.put("kaptcha.textproducer.char.length", "5");
        Config config = new Config(this.props);
        this.kaptchaProducer = config.getProducerImpl();
        this.sessionKeyValue = config.getSessionKey();
        this.sessionKeyDateValue = config.getSessionDate();
    }

    /**
     * 向页面输出一张验证码图片
     *
     * @param req  request
     * @param resp response
     */
    public void captcha(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Cache-Control", "no-store, no-cache");
        resp.setContentType("image/jpeg");
        String capText = randomCaptcha();
//        req.getSession().setAttribute(this.sessionKeyValue, capText);
//        req.getSession().setAttribute(this.sessionKeyDateValue, new Date());
        captchaService.create(CaptchaService.KEY_ACCOUNT,req.getSession().getId(), capText);
        BufferedImage bi = this.kaptchaProducer.createImage(capText);
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(bi, "jpg", out);
//        req.getSession().setAttribute(this.sessionKeyValue, capText);
//        req.getSession().setAttribute(this.sessionKeyDateValue, new Date());
    }

    /**
     * 获取图片验证码的文本格式
     *
     * @param req request
     */
    public String getGeneratedKey(HttpServletRequest req) {
        return captchaService.get(CaptchaService.KEY_ACCOUNT,req.getSession().getId());
    }

    /**
     * 生成一个激活验证码
     */
    public String randomCaptcha() {
        return this.kaptchaProducer.createText();
    }

    /**
     * 比较验证码
     *
     * @param inputCaptcha 用户输入验证码
     * @param captcha      验证码
     */
    public boolean verification(String inputCaptcha, String captcha) {
        return captchaService.verification(inputCaptcha, captcha);
    }
}
